package com.easychat.websocket;

import com.easychat.entity.dto.MessageSendDTO;
import com.easychat.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @Author: yudaxian
 * @Description: 消息处理器
 * @DateTime: 2024/8/24 15:01
 **/
@Slf4j
@Component("messageHandler")
public class MessageHandler {

    private static final String MESSAGE_TOPIC = "message.topic";

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private ChannelContextUtils channelContextUtils;

    @PostConstruct
    public void lisenMessage() {
        RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);
        rTopic.addListener(MessageSendDTO.class, (MessageSendDTO, sendDTO) -> {
            log.info("收到广播消息：{}", JsonUtils.convertJson2Json(sendDTO));
            channelContextUtils.sendMessage(sendDTO);
        });
    }

    public void sendMessage(MessageSendDTO messageSendDTO) {
        // 发消息都是往topic里面发
        RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);
        rTopic.publish(messageSendDTO);
    }
}
